package com.hx.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 封装创建sqlsession对象一个工具类
 * 获取sqlsession:sqlSessionUtils.getsqlsession*
 */
public class SqlSessionUtils {

    //定义一个静态方法，进行封装
    public static SqlSession getSqlsession() throws IOException {
        //声明变量在方法try的外
        SqlSession sqlSession=null;
        try{
            //加载核心配置文件mybatis-config.xml
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //创建工厂构造对象
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            //创建会话工厂
            final SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
            //生产会话
            sqlSession = sqlSessionFactory.openSession(true);
            //逻辑代码
        }catch (Exception e){
            //逻辑代码发生异常时输出异常
            e.printStackTrace();
        }
        //返回sqlsession对象
        return sqlSession;
    }
}
